//
//  RegistViewController.m
//  PCNews
//
//  Created by PengchengWang on 16/3/8.
//  Copyright © 2016年 pengchengWang. All rights reserved.
//

#import "RegistViewController.h"
#import <AVOSCloud.h>

@interface RegistViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UITextField *txtUserName;

@property (weak, nonatomic) IBOutlet UITextField *txtPwd;

@property (weak, nonatomic) IBOutlet UITextField *txtRePwd;

@property (weak, nonatomic) IBOutlet UITextField *txtMail;

@property (weak, nonatomic) IBOutlet UITextField *txtPhone;

@property (weak, nonatomic) IBOutlet UIImageView *imgUserIcon;

@end

@implementation RegistViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setViews];
    // Do any additional setup after loading the view from its nib.
}

- (IBAction)btnRegistAction:(id)sender {
    if (self.txtRePwd.text.length == 0||self.txtUserName.text.length == 0||self.txtPwd.text.length == 0) {
        UIAlertController *alterCon = [UIAlertController alertControllerWithTitle:@"注册失败" message:@"用户名/密码有误" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actionPwdErr = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:nil];
        [alterCon addAction:actionPwdErr];
        [self presentViewController:alterCon animated:YES completion:nil];
    }
    else{
        if ([self.txtPwd.text isEqualToString:self.txtRePwd.text]) {
            //创建AVObject对象上传数据
            AVObject *userInfoUpLoad = [AVObject objectWithClassName:@"_User"];
            [userInfoUpLoad setObject:self.txtUserName.text forKey:@"username"];
            [userInfoUpLoad setObject:self.txtPwd.text forKey:@"password"];
            if (self.txtMail.text.length) {
                [userInfoUpLoad setObject:self.txtMail.text forKey:@"email"];
            }
            if (self.txtPhone.text.length) {
                [userInfoUpLoad setObject:self.txtPhone.text forKey:@"mobilePhoneNumber"];
            }
            //异步保存数据
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.mode = MBProgressHUDModeText;
            hud.labelText = @"正在注册中,请耐心等待......";
            [userInfoUpLoad saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (succeeded) {
                    UIImage *image = self.imgUserIcon.image;
                    //将图片对象转换为NSData数据类型
                    NSData *imageData = UIImagePNGRepresentation(image);
                    //创建AVFile对象保存图片
                    AVFile *imageFile = [AVFile fileWithName:@"userIcon.png" data:imageData];
                    //创建AVObject对象上传数据
                    AVObject *userIconUpLoad = [AVObject objectWithClassName:@"UserIcon"];
                    [userIconUpLoad setObject:self.txtUserName.text forKey:@"username"];
                    [userIconUpLoad setObject:imageFile forKey:@"userIcon"];
                    [userIconUpLoad saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        if (succeeded) {
                            UIAlertController *alterCon = [UIAlertController alertControllerWithTitle:@"注册成功" message:@"恭喜你成为PC新闻用户" preferredStyle:UIAlertControllerStyleAlert];
                            UIAlertAction *actionSucceed = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                                [self.navigationController popViewControllerAnimated:YES];
                            }];
                            [alterCon addAction:actionSucceed];
                            [self presentViewController:alterCon animated:YES completion:nil];
                            hud.hidden = YES;
                        }
                        
                        
                    }];
                    
                } else {
                    UIAlertController *alterCon = [UIAlertController alertControllerWithTitle:@"注册失败" message:[NSString stringWithFormat:@"%@",error] preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *actionSucceed = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:nil];
                    [alterCon addAction:actionSucceed];
                    [self presentViewController:alterCon animated:YES completion:nil];
                    hud.hidden = YES;
                }
            }];
        }
        else{
            UIAlertController *alterCon = [UIAlertController alertControllerWithTitle:@"注册失败" message:@"两次输入密码不一致,重新确认密码" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *actionPwdErr = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                self.txtPwd.text = nil;
                self.txtRePwd.text = nil;
            }];
            [alterCon addAction:actionPwdErr];
            [self presentViewController:alterCon animated:YES completion:nil];
        }
    }
}

- (IBAction)btnCancelAction:(id)sender {
      [self.navigationController popToRootViewControllerAnimated:YES];
}


-(void)setViews{
    self.navigationItem.hidesBackButton = YES;
    UILabel *lblTitle = [[UILabel alloc]initWithFrame:CGRectMake(260, 0, 100, 40)];
    lblTitle.text = @"欢迎注册 PC新闻";
    lblTitle.textColor = [UIColor cyanColor];
    self.navigationItem.titleView = lblTitle;
    UITapGestureRecognizer *tapImgGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapImgAction)];
    [self.imgUserIcon addGestureRecognizer:tapImgGesture];
    UITapGestureRecognizer *tapRootView = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapRootView)];
    [self.view addGestureRecognizer:tapRootView];
    
}

-(void)tapImgAction{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"设置头像" message:@"选择您想使用的方式设置头像" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *actionPhotos = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self fromPhotos];
    }];
    UIAlertAction *actionCamera = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self fromCamera];
    }];
    UIAlertAction *actionPhotoLibrary = [UIAlertAction actionWithTitle:@"图库" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self fromPhotoLibrary];
    }];
    UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"算了" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:actionPhotos];
    [alert addAction:actionCamera];
    [alert addAction:actionPhotoLibrary];
    [alert addAction:actionCancel];
    [self presentViewController:alert animated:YES completion:nil];

}

-(void)tapRootView{
    [self.view endEditing:YES];
}

//UIImagePickerController调用系统相机/相册/图库
//必须遵从两个协议:<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
//调用相册
-(void)fromPhotos{
    //创建UIImagePickerController对象
    UIImagePickerController *imp=[[UIImagePickerController alloc]init];
    //.sourceType设置对象类型(相机/相册/图库)
    imp.sourceType=UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    //设置代理(目的:为了让这个对象执行协议中的方法)
    imp.delegate=self;
    //设置获取出来的照片是否可以编辑
    imp.allowsEditing=YES;
    //模态推出视图
    [self presentViewController:imp animated:YES completion:nil];
}

//调用系统相机方法
-(void)fromCamera{
    //判断是否能够调用相机功能
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        //创建UIImagePickerController对象
        UIImagePickerController *imp=[[UIImagePickerController alloc]init];
        //UIImagePickerController为调用相机类型
        imp.sourceType=UIImagePickerControllerSourceTypeCamera;
        //设置代理
        imp.delegate=self;
        imp.allowsEditing = YES;
        //模态推出视图
        [self presentViewController:imp animated:YES completion:nil];
    }else{
        UIAlertView *alert =[[UIAlertView alloc]initWithTitle:@"没有相机" message:@"您的设备不支持相机功能" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
        [alert show];
    }
}

//调用图库
-(void)fromPhotoLibrary{
    UIImagePickerController *imp=[[UIImagePickerController alloc]init];
    imp.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
    imp.delegate=self;
    imp.allowsEditing=YES;
    [self presentViewController:imp animated:YES completion:nil];
}

//点击图库中相片触发事件,并将点击的图片返回
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //设置imageView为获取到的图片,使用KVC方式获取,"UIImagePickerControllerOriginalImage"系统默认值
    self.imgUserIcon.image=[info valueForKey:@"UIImagePickerControllerEditedImage"];
    //模态窗口返回
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//点击右上角Cancel(取消)按钮触发事件
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissModalViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
